# $Id: Menu.pm,v 1.2 2004/04/27 14:26:22 ibo Exp $
package CGI::FOGE2::ViewGen;

use strict;
use CGI::FOGE2::Tools;

our @ISA = qw();

sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    
    my %args = @_;
    my @mandatory_keys = ();
    my $self = {
	form => $args{form},
    };

    bless ($self, $class);
    return $self;
}

sub setform {
    my $self = shift;
    my ($form) = @_;
    $self->{form} = $form;
}

sub get_sql_structure {
    my $self = shift;
    my $form = $self->{form};
    my %tables = ();
    
    for my $section (@{$form->{sections}}) {
	my $table = $section->get_table_name();
	for my $question (@{$section->{questions}}) {
	    push @{$tables{$table}}, ${$question->generate_field_names()}[0];
	}
    }

    return \%tables;
}

sub serve {
    my $self = shift;
    my $form = $self->{form};
    my $out = CGI::header($form->{http_headers});
    $out .= CGI::start_html( -title => "Choose columns to show",
			     -meta => {'Content-Type' => 'text/html; charset=ISO-8859-1'},
			     -style => $form->{css},
			     );

    $out .= "<center><div class='FOGE2'>";
    $out .= CGI::start_form('post', CGI::self_url());
    $out .= CGI::h1("Choose columns to show");

    print $out;
    foreach my $section (@{$form->{sections}}) {
	print $self->serve_section($section);
    }

    $out = CGI::p();
    $out .= CGI::hr();
    $out .= CGI::submit(-name => 'action', 
                  -value => 'see',
                  -class => 'formsubmit');
    $out .= CGI::hidden (-name =>'chooseview',
			 -value => 'on',
			 );
    
    $out .= CGI::end_form();
    $out .= CGI::p();
    $out .= $form->generate_foge_footer();
    $out .= "</div></center>";
    $out .= CGI::end_html();
    print $out, "\n";
}

sub serve_section {
    my $self = shift;
    my $section = shift;

    my $has_prolog = defined $section->{prolog};
    my $has_epilog = defined $section->{epilog};

    my $out = '';
    $out .= CGI::h2({-class => "sectitle"}, $section->{title});
    $out .= CGI::span({-class => "sechead"},  $section->{prolog}) if $has_prolog;

    my $question_out = '';
    foreach my $question (@{$section->{questions}}) {
        $question_out .= $self->serve_question($question);
    }
    $out .= CGI::table($question_out);
    $out .= CGI::span({-class => "sechead"},  $section->{epilog}) if $has_epilog;

    return $out;   
}

sub serve_question {
    my $self = shift;
    my $question = shift;
    my $names = $question->generate_field_names();
    my $name = $names->[0];

    return table3cols($question->{title}, $question->{ismandatory},
		      CGI::checkbox( -name => 'view',
				     -checked => 1,
				     -value => $name,
				     -label => '',
				     ));
}



1;
